<?php

namespace App\Store\Controllers\Financial\Business;

use App\Common\Services\Common;
use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use Maatwebsite\Excel\Facades\Excel;

class SalesSummaryController extends Controller
{

    /**
     * 入库汇总
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getlist(Request $request)
    {
        $data = $this->getdata($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    /**
     *
     * 入库汇总导出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function doexport(Request $request)
    {
        $data = $this->getdata($request);

        $start_time = $request->start_time;
        $end_time = $request->end_time;
        if (!$data) {
            return response()->json(['code' => '001', 'msg' => '导出失败']);
        }

        $store_id = $request['store_id'];
        $store_name = SiteStore::query()->where('id', $store_id)->value('store_name');
        $strTime = '';
        if (!empty($start_time) && !empty($end_time)) {
            $strTime = '时间:' . date('Y-m-d', strtotime($start_time)) . '-' . date('Y-m-d', strtotime($end_time));
        }
        $row = [
            ['goods_category_id' => '销售汇总表'],
            ['goods_category_id' => '所属门店：' . $store_name . "  " . $strTime],
            [
                'goods_category_id' => '商品类别',
                'total_count' => '总件数',
                'total_piece_weight' => '总件重',
                'total_netglod_weight' => '总金重',
                'total_label_price' => '商品标价',
                'total_total_money' => '销售金额',
                'total_real_total_money' => '实收金额',
                'total_performance' => '销售业绩',
                'total_cost_fee' => '总成本',
                'type_name' => '销售类型',
                'goods_style_id' => '款式',
                'count' => '件数',
                'piece_weight' => '件重',
                'netglod_weight' => '金重',
                'label_price' => '商品标价',
                'total_money' => '销售金额',
                'real_total_money' => '实收金额',
                'performance' => '销售业绩',
                'cost_fee' => '成本',
            ]];
        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[2]['total_cost_fee']);
            unset($row[2]['cost_fee']);
        }
        $initcont = count($row) + 1;
        $mergecell = [];
        foreach ($data as $val) {
            $mergecell[] = 'A' . $initcont . ':A' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'B' . $initcont . ':B' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'D' . $initcont . ':D' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'E' . $initcont . ':E' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'F' . $initcont . ':F' . $initcont + count($val['style_list']) - 1;
            $initcont = $initcont + count($val['style_list']);
            foreach ($val['style_list'] as $k1 => $v) {
                if ($k1 == 0) {
                    $exceldata[] = [
                        'goods_category_id' => $val['category_name'],
                        'total_count' => $val['count'],
                        'total_piece_weight' => $val['total_piece_weight'],
                        'total_netglod_weight' => $val['total_netglod_weight'],
                        'total_label_price' => $val['label_price'],
                        'total_total_money' => $val['total_money'],
                        'total_real_total_money' => $val['real_total_money'],
                        'total_performance' => $val['performance'],
                        'total_cost_fee' => $val['total_cost_fee'],
                        'type_name' => $val['type_name'],
                        'goods_style_id' => $v['style_name'],
                        'count' => $v['count'],
                        'piece_weight' => $v['total_piece_weight'],
                        'netglod_weight' => $v['total_netglod_weight'],
                        'label_price' => $v['label_price'],
                        'total_money' => $v['total_money'],
                        'real_total_money' => $v['real_total_money'],
                        'performance' => $v['performance'],
                        'cost_fee' => $v['total_cost_fee'],

                    ];
                } else {
                    $exceldata[] = [
                        'goods_category_id' => $val['category_name'],
                        'total_count' => $val['count'],
                        'total_piece_weight' => $val['total_piece_weight'],
                        'total_netglod_weight' => $val['total_netglod_weight'],
                        'total_label_price' => $val['label_price'],
                        'total_total_money' => $val['total_money'],
                        'total_real_total_money' => $val['real_total_money'],
                        'total_performance' => $val['performance'],
                        'total_cost_fee' => $val['total_cost_fee'],
                        'type_name' => $val['type_name'],
                        'goods_style_id' => $v['style_name'],
                        'count' => $v['count'],
                        'piece_weight' => $v['total_piece_weight'],
                        'netglod_weight' => $v['total_netglod_weight'],
                        'label_price' => $v['label_price'],
                        'total_money' => $v['total_money'],
                        'real_total_money' => $v['real_total_money'],
                        'performance' => $v['performance'],
                        'cost_fee' => $v['total_cost_fee'],
                    ];
                }
            }
        }
        $filename = '销售汇总表导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, [], $mergecell), $filename);
    }


    /**
     *
     * 数据处理
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function getdata(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $cateList = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get(['category_name', 'id'])
            ->pluck('category_name', 'id')
            ->toArray();

        $styleList = GoodsStyle::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get(['style_name', 'id'])
            ->pluck('style_name', 'id')
            ->toArray();

        $where = [];
        $type = (int)$request['type'] ?? 0;
        $store_id = $request['store_id'] ?? 0;
        $where[] = ['cp_id', '=', $cp_id];
        $where[] = ['audit_status', '<>', 3];

        if (!empty($store_id)) {
            $where[] = ['store_id', '=', $store_id];
        }

        if (!empty($request['goods_style_id'])) {
            $where[] = ['goods_style_id', '=', $request['goods_style_id']];
        }

        if (!empty($request['goods_category_id'])) {
            $where[] = ['goods_category_id', '=', $request['goods_category_id']];
        }

        // 权限
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        $store_ids = is_array($store_ids) ? $store_ids : ($store_ids > 0 ? [$store_ids] : []);

        $cateIds = [];
        // 查询柜组
        if (!empty($request['goods_cabinetgroup_id'])) {
            $cateIds = GoodsCategory::query()
                ->where(['goods_cabinetgroup_id' => $request['goods_cabinetgroup_id'], 'is_del' => 1, 'cp_id' => $cp_id])
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->pluck('id')
                ->toArray();
        }
        // 时间段查询
        $start_time = $request['start_time'];
        $end_time = $request['end_time'];

        if (!empty($start_time) && !empty($end_time)) {

            $start_time = (!is_numeric($start_time) && strtotime($start_time) > 0) ? strtotime($start_time) : intval($start_time);
            $end_time = (!is_numeric($end_time) && strtotime($end_time) > 0) ? strtotime($end_time) : intval($end_time);
            $start_time = strtotime(date('Y-m-d', $start_time) . ' 00:00:00');
            $end_time = strtotime(date('Y-m-d', $end_time) . ' 23:59:59');

            $where[] = ['order_at', '>=', $start_time];
            $where[] = ['order_at', '<=', $end_time];
        }


        // 1销售，2上柜
        if ($type == 1) {
            $where[] = ['red_status', '=', 1];
            $list = OrderSalesGoods::query()
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($cateIds) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_style_id', 'goods_category_id', 'count', 'weight', 'is_gram', 'label_price', 'total_money', 'real_total_money', 'performance', 'total_cost_fee', 'goodsinfo'])
                ->toArray();


            foreach ($list as &$item) {
                $goodsinfo = json_decode($item['goodsinfo'], true);
                unset($item['goodsinfo']);
                $item['total_piece_weight'] = 0;
                if ($item['is_gram'] == 2) {
                    if ($goodsinfo['is_code_more'] == 2) {
                        $item['total_netglod_weight'] = $item['weight'];
                    } else {
                        $item['total_netglod_weight'] = $item['weight'];
                        $item['total_piece_weight'] = $goodsinfo['piece_weight'] * $item['count'];
                    }
                } else {
                    $item['total_netglod_weight'] = $goodsinfo['netglod_weight'] * $item['count'];
                    $item['total_piece_weight'] = $item['weight'];
                }
            }

        } else {

            // 销售开单上柜
            $salesRecovery = OrderSalesRecoveryGoods::query()
                ->where('change_type', 2)
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_style_id', 'goods_category_id', 'count', 'weight', 'loss_weight', 'recovery_type', 'd_price', 'is_code_more', 'total_money', 'money', 'sales_goods_performance', 'total_cost_fee'])
                ->toArray();

            // print_r($salesRecovery);exit;


            // 纯回收开单上柜
            $recovery = OrderRecoveryGoods::query()
                ->where('change_type', 2)
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_style_id', 'goods_category_id', 'count', 'weight', 'loss_weight', 'recovery_type', 'd_price', 'is_code_more', 'total_money', 'money', 'sales_goods_performance', 'total_cost_fee'])
                ->toArray();


            $list = array_merge($salesRecovery, $recovery);
            $list = array_values($list);

            // print_r($list);exit;


            foreach ($list as &$val) {
                $val['total_piece_weight'] = 0;
                $val['total_netglod_weight'] = 0;
                $val['label_price'] = $val['d_price'];

                if ($val['recovery_type'] == 1) {
                    if ($val['is_code_more'] == 2) {
                        $val['total_netglod_weight'] = $val['weight'] - $val['loss_weight'];
                    } else {
                        $val['total_netglod_weight'] = ($val['weight'] - $val['loss_weight']) * $val['count'];
                    }
                } else {
                    $val['total_piece_weight'] = ($val['weight'] - $val['loss_weight']) * $val['count'];
                }

                $val['total_piece_weight'] = $val['total_piece_weight'] > 0 ? -$val['total_piece_weight'] : 0;
                $val['total_netglod_weight'] = $val['total_netglod_weight'] > 0 ? -$val['total_netglod_weight'] : 0;
                $val['count'] = -$val['count'];
                $val['total_money'] = -$val['total_money'];
                $val['real_total_money'] = -$val['money'];
                $val['performance'] = -$val['sales_goods_performance'];
                $val['total_cost_fee'] = -$val['total_cost_fee'];
            }

        }


        $groupData = [];
        foreach ($list as &$val) {
            $val['category_name'] = $cateList[$val['goods_category_id']] ?? '';
            $val['style_name'] = $styleList[$val['goods_style_id']] ?? '';
            $val['total_piece_weight'] = $val['total_piece_weight'] * 1000;
            $val['total_netglod_weight'] = $val['total_netglod_weight'] * 1000;
            $val['label_price'] = $val['label_price'] * $val['count'];
            $groupData[$val['goods_category_id']][] = $val;
        }

        $newData = [];
        foreach ($groupData as $goods_category_id => $group) {
            $data = [];
            $data['goods_category_id'] = $goods_category_id;
            $data['category_name'] = $cateList[$goods_category_id] ?? '';
            $data['count'] = array_sum(array_column($group, 'count'));
            $data['total_piece_weight'] = bcdiv(array_sum(array_column($group, 'total_piece_weight')), 1000, 3);
            $data['total_netglod_weight'] = bcdiv(array_sum(array_column($group, 'total_netglod_weight')), 1000, 3);
            $data['label_price'] = bcdiv(array_sum(array_column($group, 'label_price')), 100, 2);
            $data['total_cost_fee'] = bcdiv(array_sum(array_column($group, 'total_cost_fee')), 100, 2);
            $data['performance'] = bcdiv(array_sum(array_column($group, 'performance')), 100, 2);
            $data['total_money'] = bcdiv(array_sum(array_column($group, 'total_money')), 100, 2);
            $data['real_total_money'] = bcdiv(array_sum(array_column($group, 'real_total_money')), 100, 2);
            $data['type_name'] = $type == 1 ? "销售" : '上柜';

            // 分组
            $styleArr = [];
            foreach ($group as $g) {
                $styleArr[$g['goods_style_id']][] = $g;
            }

            $styleData = [];
            foreach ($styleArr as $goods_style_id => $item) {
                $st = [];
                $st['goods_style_id'] = $goods_style_id;
                $st['style_name'] = $styleList[$goods_style_id] ?? '';
                $st['count'] = array_sum(array_column($item, 'count'));
                $st['total_piece_weight'] = bcdiv(array_sum(array_column($item, 'total_piece_weight')), 1000, 3);
                $st['total_netglod_weight'] = bcdiv(array_sum(array_column($item, 'total_netglod_weight')), 1000, 3);
                $st['label_price'] = bcdiv(array_sum(array_column($item, 'label_price')), 100, 2);
                $st['total_cost_fee'] = bcdiv(array_sum(array_column($item, 'total_cost_fee')), 100, 2);
                $st['performance'] = bcdiv(array_sum(array_column($item, 'performance')), 100, 2);
                $st['total_money'] = bcdiv(array_sum(array_column($item, 'total_money')), 100, 2);
                $st['real_total_money'] = bcdiv(array_sum(array_column($item, 'real_total_money')), 100, 2);
                $styleData[] = $st;
            }

            $data['style_list'] = $styleData;

            $newData[] = $data;
        }
        return $newData;
    }


    /**
     * 明细列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getdetail(Request $request)
    {
        $list = $this->getDetialData($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    /**
     * 导出
     */
    public function detailexport(Request $request)
    {
        $type = $request->type ?? 0;
        $list = $this->getDetialData($request)['list'];
        if ($type == 1) {
            // 销售开单商品明细
            $row = [
                ['table_header' => '销售汇总-销售'],
                [
                    'order_sn'=>'订单号',
                    'order_type'=>'订单类型',
                    'store' => '所属门店',
                    'order_at'=>'下单日期',
                    'shopping_account_info'=>'导购',
                    'goods_name' => '商品名称',
                    'goods_sn_code' => '条码',
                    'goods_catefory' => '商品类别',
                    'style_name' => '款式',
                    'count' => '数量',
                    'cf_no' => '证书号',
                    'label_price_old' => '商品标价',
                    'label_price' => '标价',
                    'discount' => '折扣',
                    'total_money' => '应收金额',
                    'weight_old' => '货重',
                    'weight' => '销售重量',
                    'price' => '销售单价',
                    'goods_costs_price' => '商品工费单价',
                    'goods_costs_price_total' => '商品工费',
                    'sale_costs_price' => '销售工费单价',
                    'sale_costs_price_total' => '销售工费',
                    'add_fee1' => '附加费1',
                    'add_fee2' => '附加费2',
                    'gemstone_fee1' => '宝石费1',
                    'gemstone_fee2' => '宝石费2',
                    'truncate_glod_weight' => '截金重量',
                    'truncate_glod_money' => '截金金额',
                    'real_total_money' => '实收金额',
                    'commission_total' => '提成',
                    'order_points' => '获取积分',
                    'performance' => '业绩金额',
                    'sales_price' => '销售金价',
                    'old_recovery_price' => '返厂金价',
                    'brand_name' => '品牌',
                    'real_name' => '会员姓名',
                    'mobile' => '会员电话',
                    'pricetype_name' => '价格类型',
                    'is_exchange' => '是否已换',
                    'main_stone_weigth' => '主石重',
                    'main_stone_count' => '主石数',
                    'main_stone_val' => '主石值',
                    'other_stone_weigth' => '副石重',
                    'other_stone_count' => '副石数',
                    'other_stone_val' => '副石值',
                    'remark' => '备注'
                ]];
            $exceldata = [];
            foreach ($list as $val) {
                $goods = json_decode($val['goodsinfo'], true);

//                //商品工费单件=商品的克销工费+商品的件销工费
//                //商品工费 =克销工费*重量+件销工费*数量
//                $goods_costs_price = bcadd($goods['gramprice_fee'] ?? 0, $goods['pieceprice_fee'] ?? 0);
//                $goods_costs_price_total = bcadd(($goods['gramprice_fee'] ?? 0) * ($val['weight'] ?? 0), ($goods['pieceprice_fee'] ?? 0) * ($val['count'] ?? 0), 2);
//
//                //销售工费单件=商品的克销工费+商品的件销工费-工费优惠填的值
//                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
//                $sale_costs_price = bcadd($goods['gramprice_fee'] ?? 0, $goods['pieceprice_fee'] ?? 0) - ($val['cost_price_discount'] ?? 0);
//                $sale_costs_price_total = $goods_costs_price_total - ($val['cost_price_discount'] ?? 0) * ($val['weight'] ?? 0);

//               2025-10-16 再次修改公式调整
                //商品工费单价（字段应该是：商品克销工费）=商品的克销工费
                //商品工费 =克销工费*重量+件销工费
                $goods_costs_price = ($goods['gramprice_fee'] ?? 0);
                $goods_costs_price_total = bcadd(($goods['gramprice_fee'] ?? 0) * ($val['weight'] ?? 0), ($goods['pieceprice_fee'] ?? 0), 2);

                //销售工费单价（字段应该是：销售克销工费）=商品的克销工费-工费优惠填的值
                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
                $sale_costs_price = ($goods['gramprice_fee'] ?? 0) - ($val['cost_price_discount'] ?? 0);
                $sale_costs_price_total = $goods_costs_price_total - ($val['cost_price_discount'] ?? 0) * ($val['weight'] ?? 0);

                $exceldata[] = [
                    'store' => $val['storeinfo']['store_name'] ?? '',
                    'order_sn'=>$val['orderinfo']['order_sn']??'',
                    'order_type'=>'销售开单',
                    'order_at'=> ($val['order_at']??0)>0?date('Y-m-d H:i:s',$val['order_at']): '',
                    'shopping_account_info'=>$val['shoppingaccountinfo1']['real_name']?? '',
                    'goods_name' => $val['goods_name'],
                    'goods_sn_code' => "{$val['goods_sn_code']} ",
                    'goods_catefory' => $goods['goods_category']['category_name'] ?? '',
                    'style_name'=>$goods['goods_style']['style_name']?? '',
                    'count' => $val['count'],
                    'cf_no' => $goods['cf_no'],
                    'label_price_old' => $val['label_price_old'] > 0 ? $val['label_price_old'] / 100 : 0,
                    'label_price' => $val['label_price'] > 0 ? $val['label_price'] / 100 : 0,
                    'discount' => $val['discount'],
                    'total_money' => $val['total_money'] > 0 ? $val['total_money'] / 100 : 0,
                    'weight_old' => $val['weight_old'] ?? '',
                    'weight' => $val['weight'],
                    'price' => ($val['price'] ?? 0) > 0 ? $val['price'] / 100 : '',
                    'goods_costs_price' => ($goods_costs_price) > 0 ? $goods_costs_price / 100 : 0,
                    'goods_costs_price_total' => ($goods_costs_price_total) > 0 ? $goods_costs_price_total / 100 : 0,
                    'sale_costs_price' => $sale_costs_price > 0 ? $sale_costs_price / 100 : 0,
                    'sale_costs_price_total' => $sale_costs_price_total > 0 ? $sale_costs_price_total / 100 : 0,
                    'add_fee1' => $val['add_fee1'] > 0 ? $val['add_fee1'] / 100 : 0,
                    'add_fee2' => $val['add_fee2'] > 0 ? $val['add_fee2'] / 100 : 0,
                    'gemstone_fee1' => $val['gemstone_fee1'] > 0 ? $val['gemstone_fee1'] / 100 : 0,
                    'gemstone_fee2' => $val['gemstone_fee2'] > 0 ? $val['gemstone_fee2'] / 100 : 0,
                    'truncate_glod_weight' => $val['truncate_glod_weight'] ?? '',
                    'truncate_glod_money' => $val['truncate_glod_money'] > 0 ? $val['truncate_glod_money'] / 100 : 0,
                    'real_total_money' => $val['real_total_money'] > 0 ? $val['real_total_money'] / 100 : 0,
                    'commission_total' => ($val['commission1_total'] + $val['commission2_total']) > 0 ? ($val['commission1_total'] + $val['commission2_total']) / 100 : 0,
                    'order_points' => $val['order_points'],
                    'performance' => $val['performance'] / 100,
                    'sales_price' => $val['sales_price'] > 0 ? $val['sales_price'] / 100 : 0,
                    'old_recovery_price' => $val['sales_price'] > 0 ? $val['old_recovery_price'] / 100 : 0,
                    'brand_name' => $goods['goods_brand']['brand_name']?? '',
                    'real_name' => $val['memberinfo']['real_name']?? '',
                    'mobile' => $val['memberinfo']['mobile']?? '',
                    'pricetype_name' => $goods['goods_pricetype']['pricetype_name'] ?? '',
                    'is_exchange' => $val['is_exchange'] == 1 ? '未换' : '已换',
                    'main_stone_weigth' => $goods['main_stone_weigth'] ?? '',
                    'main_stone_count' => $goods['main_stone_count'] ?? '',
                    'main_stone_val' => $goods['main_stone_val'] ?? '',
                    'other_stone_weigth' => $goods['main_stone_weigth'] ?? '',
                    'other_stone_count' => $goods['main_stone_count'] ?? '',
                    'other_stone_val' => $goods['main_stone_val'] ?? '',
                    'remark' => $val['remark'],
                ];
            }
            $filename = '销售汇总_销售导出' . time() . '.xlsx';
        } else {
            //订单号、所属门店、下单日期、导购-
            $row = [
                ['table_header' => '销售汇总-上柜'],
                [
                    'order_sn'=>'订单号',
                    'store' => '所属门店',
                    'order_type'=>'订单类型',
                    'order_at'=>'下单日期',
                    'shopping_account_info'=>'导购',
                    'change_type' => '换货方式',
                    'recovery_type' => '回收方式',
                    'goods_catefory_name' => '旧料类别',
                    'goods_sn_code' => '条码',
                    'count' => '数量',
                    'weight' => '重量',
                    'price' => '旧料单价',
                    'd_price' => '旧料标价',
                    'discount' => '折扣',
                    'dold_price' => '折旧单价',
                    'dold_fee' => '折扣工费',
                    'loss_weight' => '损耗重量',
                    'money' => '回收金额',
                    'sales_price' => '牌价',
                    'old_recovery_price' => '料价',
                    'main_stone_weigth' => '主石重',
                    'clarity' => '净度',
                    'color' => '颜色',
                    'real_name' => '会员姓名',
                    'mobile' => '会员电话',
                    'remark' => '备注',
                ]];

            $exceldata = [];

            foreach ($list as $item) {

                $goodsinfo = !empty($item['salseordergoods']) ? json_decode($item['salseordergoods']['goodsinfo'], true) : [];
                $exceldata[] = [
                    'store' => $item['storeinfo']['store_name'] ?? '',
                    'order_sn'=>$item['orderinfo']['order_sn']?? '',
                    'order_type'=>'上柜',
                    'order_at'=> ($item['order_at']??0)>0?date('Y-m-d H:i:s', $item['order_at']): '',
                    'shopping_account_info'=>$item['shoppingaccountinfo1']['real_name']?? '',
                    'change_type' => (int)$item['change_type'] == 1 ? '回收' : '上柜',
                    'recovery_type' => (int)$item['recovery_type'] == 1 ? '按克' : '标价',
                    'goods_catefory_name' => $item['goods_catefory_name'] ?? '',
                    'goods_sn_code' => "{$item['goods_sn_code']} ",
                    'count' => $item['count'] ?? '',
                    'weight' => $item['weight'],
                    'price' => $item['price'] > 0 ? $item['price'] / 100 : 0,
                    'd_price' => $item['d_price'] > 0 ? $item['d_price'] / 100 : 0,
                    'discount' => $item['discount'],
                    'dold_price' => $item['dold_price'] > 0 ? $item['d_price'] / 100 : 0,
                    'dold_fee' => $item['dold_fee'] > 0 ? $item['d_price'] / 100 : 0,
                    'loss_weight' => $item['loss_weight'] ?? '',
                    'money' => $item['money'] > 0 ? $item['money'] / 100 : 0,
                    'sales_price' => ($item['sales_price'] ?? 0) > 0 ? $item['sales_price'] / 100 : '',
                    'old_recovery_price' => ($item['old_recovery_price'] ?? 0) > 0 ? $item['old_recovery_price'] / 100 : '',
                    'main_stone_weigth' => $goodsinfo['main_stone_weigth'] ?? '',
                    'clarity' => $goodsinfo['main_stone_weigth'] ?? '',
                    'color' => $goodsinfo['color'] ?? '',
                    'real_name' => $item['memberinfo']['real_name']?? '',
                    'mobile' => $item['memberinfo']['mobile']?? '',
                    'remark' => $item['remark'] ?? '',
                ];
            }
            $filename = '销售汇总_上柜导出' . time() . '.xlsx';
        }

        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 获取明细 数据
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function getDetialData(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $limit = $request->limit ?? 10;
        $page = $request->page ?? 0;

        $where = [];
        $type = (int)$request['type'] ?? 0;
        $store_id = $request['store_id'] ?? 0;
        $where[] = ['cp_id', '=', $cp_id];
        $where[] = ['audit_status', '<>', 3];

        if (!empty($store_id)) {
            $where[] = ['store_id', '=', $store_id];
        }

        if (!empty($request['goods_style_id'])) {
            $where[] = ['goods_style_id', '=', $request['goods_style_id']];
        }

        if (!empty($request['goods_category_id'])) {
            $where[] = ['goods_category_id', '=', $request['goods_category_id']];
        }

        // 权限
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        $store_ids = is_array($store_ids) ? $store_ids : ($store_ids > 0 ? [$store_ids] : []);

        $cateIds = [];
        // 查询柜组
        if (!empty($request['goods_cabinetgroup_id'])) {
            $cateIds = GoodsCategory::query()
                ->where(['goods_cabinetgroup_id' => $request['goods_cabinetgroup_id'], 'is_del' => 1, 'cp_id' => $cp_id])
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->pluck('id')
                ->toArray();
        }
        // 时间段查询
        $start_time = $request['start_time'];
        $end_time = $request['end_time'];

        if (!empty($start_time) && !empty($end_time)) {

            $start_time = (!is_numeric($start_time) && strtotime($start_time) > 0) ? strtotime($start_time) : intval($start_time);
            $end_time = (!is_numeric($end_time) && strtotime($end_time) > 0) ? strtotime($end_time) : intval($end_time);
            $start_time = strtotime(date('Y-m-d', $start_time) . ' 00:00:00');
            $end_time = strtotime(date('Y-m-d', $end_time) . ' 23:59:59');

            $where[] = ['order_at', '>=', $start_time];
            $where[] = ['order_at', '<=', $end_time];
        }


        // 1销售，2上柜
        if ($type == 1) {
            $where[] = ['red_status', '=', 1];
            $query = OrderSalesGoods::query()
                ->with(['orderinfo','memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goods_category'])
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($cateIds) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                });
            if ($page > 0) {
                $list = $query->paginate($limit)->toArray();
                return Common::paginateDataToArray($list);
            } else {
                $list['list'] = $query->get()->toArray();
            }
        } else {
            // 销售开单上柜
            $salesRecovery = OrderSalesRecoveryGoods::query()
                ->with(['orderinfo','memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'salseordergoods'])
                ->where('change_type', 2)
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_sn_code', 'pid','change_type', 'mem_id', 'store_id', 'shopping_account_id1', 'shopping_account_id2', 'goods_catefory_name', 'goods_style_id', 'goods_category_id', 'count', 'weight', 'loss_weight', 'recovery_type', 'price', 'd_price', 'is_code_more', 'total_money', 'money', 'sales_goods_performance', 'total_cost_fee', 'sales_goods_id', 'old_recovery_price', 'sales_price', 'discount', 'dold_price', 'dold_fee', 'remark','order_at'])
                ->toArray();
            // 纯回收开单上柜
            $recovery = OrderRecoveryGoods::query()
                ->with(['orderinfo','memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo'])
                ->where('change_type', 2)
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_sn_code', 'pid','change_type', 'mem_id', 'store_id', 'shopping_account_id1', 'shopping_account_id2', 'goods_catefory_name', 'goods_style_id', 'goods_category_id', 'count', 'weight', 'loss_weight', 'recovery_type', 'price', 'd_price', 'is_code_more', 'total_money', 'money', 'sales_goods_performance', 'total_cost_fee', 'sales_goods_id', 'old_recovery_price', 'sales_price', 'discount', 'dold_price', 'dold_fee', 'remark','order_at'])
                ->toArray();

            $arr = array_values(array_merge($salesRecovery, $recovery));

            foreach ($arr as &$val) {
                $val['total_piece_weight'] = 0;
                $val['total_netglod_weight'] = 0;
                $val['money'] = -$val['money'];
                $val['count'] = -$val['count'];
                $val['weight'] = -$val['weight'];
            }
            if ($page > 0) {
                $list = $this->arrayPaginate($arr, $page, $limit);
            } else {
                $list['list'] = $arr;
            }

        }
        return $list;
    }


    /**
     * 二维数组分页
     * @param array $array 原始数组
     * @param int $page 当前页码
     * @param int $pageSize 每页显示数量
     * @return array 分页后的数据
     */
    function arrayPaginate(array $array, int $page = 1, int $pageSize = 10): array
    {
        $total = count($array);
        $page = max($page, 1); // 页码最小为1
        $offset = ($page - 1) * $pageSize;
        return [
            'list' => array_slice($array, $offset, $pageSize),
            'page' => [
                'totalCount' => $total,
                'currentPage' => $page,
                'total_pages' => ceil($total / $pageSize)
            ]
        ];
    }
}
